/**
 * Author: Shen Yanqiu
 * Date: 2017-12-09
 * Time: 17:44
 *
 */
import React from 'react';
// import { Button, Row, Col } from 'antd';
// import { config } from 'utils';
// import { routerRedux } from 'dva/router';
// import styles from './index.less';
import { connect } from "dva";
import PropTypes from 'prop-types';
import { api } from 'config';
import styles from './index.less';
import { Form, Row, Col, Input, Select, Upload, Modal, Icon, Button, message } from 'antd';

const FormItem = Form.Item;
const Option = Select.Option;

class CreateOrganization extends React.Component {
  static propTypes = {
    form: PropTypes.object,
    dispatch: PropTypes.func,
    loading: PropTypes.object,
    organization: PropTypes.object,
    app: PropTypes.object,
    user: PropTypes.object,
  };
  state = {
    previewVisible: false,
    previewImage: '',
    fileList: [],
    fileDemoList: [{
      uid: -1,
      name: 'xxx.png',
      status: 'done',
      url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    }],
  };

  handleCancel = () => this.setState({ previewVisible: false });
  // 查看大图
  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };
  handleChange = ({ file, fileList }) => {
    this.setState({ fileList });
    // console.log(fileList);
    // console.log(file);
    if (file.status === "error") {
      message.error("上传失败，请重新上传！");
    } else if (file.status === "done") {
      message.success("上传成功！");
    }
  };

  render () {
    const { dispatch, loading, organization, app, user, form: {
      getFieldDecorator,
      validateFieldsAndScroll,
    } } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };
    // 上传图片
    const { previewVisible, previewImage, fileList, fileDemoList } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    const handleOK = () => {
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          return;
        }
        // console.log(this.state.fileList);
        const paperwork = [];
        this.state.fileList.forEach((item) => {
          if (item.response.Data) {
            paperwork.push(item.response.Data.File.ID);
          }
        });
        console.log(paperwork);
        if (paperwork.length === 0) {
          message.error("请上传证明图片！");
          return;
        }
        values.school = user.school.ID;
        values.paperwork = paperwork;
        values.scale = parseInt(values.scale, 10);
        dispatch({ type: 'organization/doCreate', payload: values });
      });
    };
    return (
      <div className={styles.form}>
        <div className={styles.title}>创建组织</div>
        <Form hideRequiredMark className={styles.formstyle}>
          <FormItem {...formItemLayout} label="学校" hasFeedback >
            {getFieldDecorator('school', {
              rules: [],
              initialValue: `${user.school ? user.school.Name : ''}`,
            })(<Input readOnly />)}
          </FormItem>
          <FormItem {...formItemLayout} label="名称" hasFeedback >
            {getFieldDecorator('name', {
              rules: [{
                required: true,
                message: '名称不能为空！',
              }],
            })(<Input placeholder="请选择组织名称" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="组织规模" >
            {getFieldDecorator('scale', {
              rules: [{
                required: true,
                message: '名称不能为空！',
              }],
            })(<Select placeholder={"请选择组织规模"}>
              <Option value="0">9-10人</Option>
            </Select>)}
          </FormItem>
          <Row>
            <Col sm={4} xs={4} className={styles.textRight}>
              上传证明：
            </Col>
            <Col sm={8} xs={9}>
              <Upload
                action={`${api.uploadfiles}`}
                headers={{ "U-Access-Token": user.token }}
                listType="picture-card"
                fileList={fileList}
                onPreview={this.handlePreview}
                onChange={this.handleChange}
              >
                {fileList.length >= 1 ? null : uploadButton}
              </Upload>

              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </Col>
            <Col sm={4} xs={3} className={styles.textRight}>
              示例：
            </Col>
            <Col sm={8} xs={8}>
              <Upload
                listType="picture-card"
                fileList={fileDemoList}
                onPreview={this.handlePreview}
                showUploadList={{ showPreviewIcon: true, showRemoveIcon: false }}
              />
            </Col>
          </Row>
          <Row>
            <Col span={4} />
            <Col span={18} className={styles.remind}>
              <p>请提交该创建者作为社团最高管理者的证明</p>
              <p>材料（盖有公章）或者工牌，以便确保唯一性</p>
            </Col>
          </Row>
          <FormItem className={styles.bottomBtn}>
            <Button type="primary" onClick={handleOK} loading={loading.effects.doRegister}>提交</Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}
export default connect(({ loading, organization, app, user }) => ({ loading, organization, app, user }))(Form.create({})(CreateOrganization));
